package com.shi.yibanjia.controller;

import cn.hutool.core.lang.Validator;
import com.shi.yibanjia.common.Result;
import com.shi.yibanjia.entity.po.User;
import com.shi.yibanjia.service.SMSService;
import com.shi.yibanjia.service.UserService;
import com.shi.yibanjia.utils.AliYunOSSUtil;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/app/common")
public class CommonController {


    @Resource
    private SMSService smsService;

    @Resource
    private UserService userService;

    @GetMapping("/generate-code/{phone}")
    public Result generateCode(@PathVariable("phone") String phone) {
        if (!Validator.isMobile(phone)) {
            return Result.fail("手机号不合法");
        }
        User user = userService.getByPhone(phone);
        if (user!=null && !user.getIsEnabled()) {
            return Result.fail("账号已被禁用");
        }
        return smsService.sendSMS(phone);
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile file, HttpServletRequest request) {
        System.out.println(request.getMethod());
        String filePath = AliYunOSSUtil.putObject(file);
        return Result.ok(filePath);
    }

    @DeleteMapping("/fileRemove")
    public Result remove(@RequestBody String url) {
        AliYunOSSUtil.removeObject(url.replace(AliYunOSSUtil.getBaseUrl(), ""));
        return Result.ok();
    }

}
